import React, { useEffect, useState } from 'react';
import { Modal, Transfer, message } from 'antd';
import { getGroupUsers, updateGroupUsers } from '@/services/auth/group';

import { TMemberData } from '../data';

interface Props {
  /**
   * 用户组 ID
   */
  groupId: string;
  /**
   * 是否显示
   */
  visible: boolean;
  onCancel: () => void;
  onOk: () => void;
}

export default function MemberModal(props: Props) {
  const { groupId, visible } = props;

  const [state, setState] = useState<TMemberData>({
    addList: [],
    allList: [],
  });

  const loadData = async (gid: string) => {
    const res = await getGroupUsers(gid);
    if (res.code === 0) {
      setState({
        addList: res.data.addList,
        allList: res.data.allList,
      });
    }
  };

  useEffect(() => {
    if (groupId) {
      loadData(groupId);
    }
  }, [groupId]);

  const handleChange = (targetKeys: string[]) => {
    setState((s) => ({
      addList: [...targetKeys],
      allList: s.allList,
    }));
  };

  const cancel = () => {
    if (typeof props.onCancel === 'function') {
      props.onCancel();
    }
  };

  const onOk = () => {
    if (typeof props.onOk === 'function') {
      props.onOk();
    }
  };

  const onUpdateMember = async () => {
    const { addList } = state;
    const res = await updateGroupUsers(groupId, { idList: addList });
    if (res.code === 0) {
      message.success('修改成功！');
      onOk();
    }
  };

  return (
    <Modal
      title="成员管理"
      visible={visible}
      onOk={() => onUpdateMember()}
      onCancel={() => cancel()}
      okButtonProps={{}}
      okText="确定"
    >
      <Transfer
        dataSource={state.allList}
        titles={['未添加', '已添加']}
        targetKeys={state.addList}
        onChange={handleChange}
        render={(item) => item.title}
      />
    </Modal>
  );
}
